package com.zxjbyte.yiyi.framework.cdc.mysql;

import com.github.shyiko.mysql.binlog.BinaryLogClient;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicReference;

/**
 * MySQL Binlog Connector生命周期事件的监听器
 *
 * @Author zhangxingjia
 * @Date 2025/8/28 17:22
 * @Version: 1.0
 */
@Slf4j
public class BinlogLifecycleListener implements BinaryLogClient.LifecycleListener{

    AtomicReference<BinaryLogClient> client = new AtomicReference<>(null);
    AtomicReference<Exception> exception = new AtomicReference<>(null);

    @Override
    public void onConnect(BinaryLogClient binaryLogClient) {
        log.info(">>>> [cdc-mysql] Binlog client connected successfully");
        client.set(binaryLogClient);
        exception.set(null);
    }

    @Override
    public void onCommunicationFailure(BinaryLogClient binaryLogClient, Exception e) {
        log.error(">>>> [cdc-mysql] Binlog communication failure occurred", e);
        client.set(binaryLogClient);
        exception.set(e);
    }

    @Override
    public void onEventDeserializationFailure(BinaryLogClient binaryLogClient, Exception e) {
        log.error(">>>> [cdc-mysql] Event deserialization failed", e);
        client.set(binaryLogClient);
        exception.set(e);
    }

    @Override
    public void onDisconnect(BinaryLogClient binaryLogClient) {
        log.info(">>>> [cdc-mysql] Binlog client disconnected");
        client.set(binaryLogClient);
    }

    public BinaryLogClient getClient() {
        return client.get();
    }

    public Exception getException() {
        return exception.get();
    }
}
